/****************************************************************************
 * Copyright (c) 2010 Torkild U. Resheim
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Torkild U. Resheim  - initial API and implementation
 *****************************************************************************/
package no.resheim.buildmonitor.hudson.ui;

import java.net.URI;
import java.net.URISyntaxException;

import no.resheim.buildmonitor.core.BuildmonitorCore;
import no.resheim.buildmonitor.core.data.Server;
import no.resheim.buildmonitor.hudson.HudsonServerFactory;

import org.eclipse.ecf.core.IContainer;
import org.eclipse.ecf.ui.IConnectWizard;
import org.eclipse.equinox.security.storage.StorageException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;

/**
 * Wizard for adding new Hudson servers for monitoring.
 * 
 * @author Torkild Ulvøy Resheim
 * @since 1.0
 */
public class ConnectWizard extends Wizard implements IConnectWizard, INewWizard {

	private ConnectWizardPage page;

	public ConnectWizard() {
	}

	@Override
	public void addPages() {
		page = new ConnectWizardPage(ConnectWizardPage.class.getSimpleName());
		addPage(page);
	}

	@Override
	public void init(IWorkbench workbench, IContainer container) {
	}

	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		setWindowTitle("New Hudson Connection");
	}

	@Override
	public boolean performFinish() {

		final String url = page.getURL();
		final String login = page.getLogin();
		final String password = page.getPassword();

		HudsonServerFactory f = new HudsonServerFactory();
		try {
			Server server = f.createInstance(new URI(url));
			BuildmonitorCore.getDefault().storeCredentials(new URI(url), login,
					password);
			BuildmonitorCore.getDefault().getServers().addServer(server, null);
			server.connect();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (StorageException e) {
			e.printStackTrace();
		}

		return true;
	}

}
